package cps

import (
	"github.com/flaravel/quanlaolao/pkg/logger"
	"github.com/flaravel/quanlaolao/pkg/model"
	"github.com/flaravel/quanlaolao/pkg/pagination"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"net/http"
)

func GetAll(r *http.Request, perPage int) ([]Cps, pagination.ViewData, error) {

	db := model.DB.Model(&Cps{}).Order("created_at desc")
	_pager := pagination.New(r,  db, route.Name2URL("cps.index"), perPage)

	viewData := _pager.Paging()

	var cps []Cps
	_ = _pager.Results(&cps)

	return cps, viewData, nil
}

func (cps *Cps) Create() (err error) {
	if err = model.DB.Create(&cps).Error; err != nil {
		logger.LogError(err)
		return err
	}

	return nil
}

func GetList(channelId int) ([]*Cps, error) {
	var cps []*Cps
	var db = model.DB

	if channelId > 0 {
		db = db.Where("channel_id = ?",channelId)
	}

	if err := db.Order("sort DESC").Find(&cps).Error; err != nil {
		return cps, err
	}

	return cps, nil
}

func Get(idstr string) (Cps, error) {
	var cps Cps
	id := types.StringToInt(idstr)
	if err := model.DB.First(&cps, id).Error; err != nil {
		return cps, err
	}

	return cps, nil
}

func (cps *Cps) Delete() (rowsAffected int64, err error) {
	result := model.DB.Delete(&cps)
	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}
	return result.RowsAffected, nil
}
func (cps *Cps) Update() (rowsAffected int64, err error) {
	result := model.DB.Save(&cps)
	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}
	return result.RowsAffected, nil
}